<template>
  <div class="user-list">
    <a-page-header
      title="用户管理"
      sub-title="管理系统中的用户账号，包括新增、编辑、删除等操作。"
    />
    <a-divider />
    <a-card class="search-card">
      <template #title>
        <span>搜索条件</span>
        <a-divider type="vertical" />
      </template>
      <a-form layout="inline">
        <a-form-item label="用户名">
          <a-input v-model:value="searchForm.username" placeholder="请输入用户名" allowClear />
        </a-form-item>
        <a-form-item label="昵称">
          <a-input v-model:value="searchForm.nickname" placeholder="请输入昵称" allowClear />
        </a-form-item>
        <a-form-item label="手机号">
          <a-input v-model:value="searchForm.phone" placeholder="请输入手机号" allowClear />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="fetchUserList">
              <template #icon><search-outlined /></template>查询
            </a-button>
            <a-button @click="() => {
              searchForm.username = '';
              searchForm.nickname = '';
              searchForm.phone = '';
              fetchUserList();
            }">
              <template #icon><reload-outlined /></template>重置
            </a-button>
            <a-button type="primary" @click="showAddModal" v-permission="'system:user:manage:add'">
              <template #icon><user-add-outlined /></template>新增用户
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-table 
        bordered
        :columns="columns" 
        :data-source="userList" 
        :loading="tableLoading" 
        :pagination="{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
        }"
        @change="handleTableChange"
        rowKey="id">
        <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
            <a-space>
                <a-button type="primary" @click="showEditModal(record)" v-permission="'system:user:manage:edit'">
                  <template #icon><edit-outlined /></template>编辑
                </a-button>
                <a-popconfirm
                title="确定要删除这个用户吗？"
                @confirm="handleDelete(record.id)"
                ok-text="确定"
                cancel-text="取消"
                >
                <a-button type="primary" danger v-permission="'system:user:manage:delete'">
                  <template #icon><delete-outlined /></template>删除
                </a-button>
                </a-popconfirm>
            </a-space>
            </template>
            <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : record.status === 2 ? 'orange' : 'red'">
                {{ record.status === 1 ? '正常' : record.status === 2 ? '待审核' : '禁用' }}
            </a-tag>
            </template>
            <template v-else-if="column.key === 'avatar'">
              <div v-if="!record.avatar" style="width: 40px; height: 40px; background-color: #f0f0f0; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #999;">暂无</div>
              <img v-else :src="`/api${record.avatar}`" alt="avatar" style="width: 40px; height: 40px; border-radius: 8px; object-fit: cover" />
            </template>
        </template>
    </a-table>

    <!-- 新增/编辑用户弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="modalVisible"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :confirmLoading="modalLoading"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState.username" :disabled="isEdit" placeholder="请输入3-20位的用户名" />
        </a-form-item>
        <a-form-item label="密码" name="password" v-if="!isEdit">
          <a-input-password v-model:value="formState.password" placeholder="请输入6-20位的密码" />
        </a-form-item>
        <a-form-item label="昵称" name="nickname">
          <a-input v-model:value="formState.nickname" placeholder="请输入用户昵称" />
        </a-form-item>
        <a-form-item label="头像" name="avatar">
          <a-upload
            v-model:file-list="fileList"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="/api/upload"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl.startsWith('data:') ? imageUrl : `/api${imageUrl}`" alt="avatar" style="width: 100%; height: 100%; border-radius: 8px; object-fit: cover" />
            <div v-else>
              <loading-outlined v-if="imageLoading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="formState.phone" placeholder="请输入手机号" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="formState.status">
            <a-select-option :value="1">正常</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
            <a-select-option :value="2">待审核</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="个人简介" name="bio">
          <a-textarea v-model:value="formState.bio" placeholder="请输入个人简介" :rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, h } from 'vue';
import { message, PageHeader } from 'ant-design-vue';
import { LoadingOutlined, PlusOutlined, SearchOutlined, ReloadOutlined, UserAddOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import axios from 'axios';
import { encryptPassword } from '@/utils/crypto';
import { checkPermission, checkAndWarnPermission } from '@/utils/permission';

export default defineComponent({
  name: 'UserList',
  components: {
    LoadingOutlined,
    PlusOutlined,
    SearchOutlined,
    ReloadOutlined,
    UserAddOutlined,
    EditOutlined,
    DeleteOutlined,
    APageHeader: PageHeader,
  },
  setup() {
    const imageUrl = ref('');
    const imageLoading = ref(false);
    const tableLoading = ref(false);
    const fileList = ref([]);

    const getBase64 = (img, callback) => {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    };

    const beforeUpload = (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('只能上传 JPG/PNG 格式的图片！');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过 2MB！');
      }
      return isJpgOrPng && isLt2M;
    };

    const handleChange = (info) => {
      if (info.file.status === 'uploading') {
        imageLoading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        if (info.file.response.code === 200) {
          formState.avatar = info.file.response.data;
          getBase64(info.file.originFileObj, (base64Url) => {
            imageUrl.value = base64Url;
            imageLoading.value = false;
          });
        } else {
          message.error('上传失败');
          imageLoading.value = false;
        }
      }
      if (info.file.status === 'error') {
        imageLoading.value = false;
        message.error('上传失败');
      }
    };

    const columns = [
      {
        title: '序号',
        key: 'index',
        width: 80,
        customRender: ({ index }) => index + 1
      },
      {
        title: '头像',
        dataIndex: 'avatar',
        key: 'avatar',
        width: 80
      },
      {
        title: '用户名',
        dataIndex: 'username',
        key: 'username',
        customRender: ({ text }) => text || '暂无'
      },
      {
        title: '昵称',
        dataIndex: 'nickname',
        key: 'nickname',
        customRender: ({ text }) => text || '暂无'
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        key: 'phone',
        customRender: ({ text }) => text || '暂无'
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email',
        customRender: ({ text }) => text || '暂无'
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        customRender: ({ text }) => text || '暂无'
      },
      {
        title: '操作',
        key: 'action',
        fixed: 'right',
        width: 200
      },
    ];

    const userList = ref([]);
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    const modalTitle = ref('');
    const isEdit = ref(false);
    const formRef = ref();
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0
    });
    const searchForm = reactive({
      username: '',
      nickname: '',
      phone: ''
    });

    const formState = reactive({
      id: null,
      username: '',
      password: '',
      nickname: '',
      avatar: '',
      phone: '',
      email: '',
      role: 'user',
      status: 1,
      bio: ''
    });

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度必须在3-20之间', trigger: 'blur' },
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度必须在6-20之间', trigger: 'blur' },
      ],
      nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
      phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
      ],
      email: [
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    };

    // 获取用户列表
    const fetchUserList = async () => {
      tableLoading.value = true;
      try {
        const params = {
          current: pagination.current,
          size: pagination.pageSize,
          ...searchForm
        };
        const response = await axios.get('/api/user/manage', { params });
        if (response.data.code === 200) {
          const { records, total, current, size } = response.data.data;
          userList.value = records;
          pagination.total = total;
          pagination.current = current;
          pagination.pageSize = size;
        } else {
          message.error(response.data.message || '获取用户列表失败');
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        message.error('获取用户列表失败');
      } finally {
        tableLoading.value = false;
      }
    };

    // 处理表格分页变化
    const handleTableChange = (pag) => {
      pagination.current = pag.current;
      pagination.pageSize = pag.pageSize;
      fetchUserList();
    };

    // 显示新增/编辑弹窗
    const showAddModal = () => {
      modalTitle.value = '新增用户';
      isEdit.value = false;
      formState.id = null;
      formState.username = '';
      formState.password = '';
      formState.nickname = '';
      formState.avatar = '';
      formState.phone = '';
      formState.email = '';
      formState.role = 'user';
      formState.status = 1;
      formState.bio = '';
      imageUrl.value = '';
      modalVisible.value = true;
    };

    const showEditModal = (record) => {
      modalTitle.value = '编辑用户';
      isEdit.value = true;
      formState.id = record.id;
      formState.username = record.username;
      formState.nickname = record.nickname;
      formState.avatar = record.avatar;
      formState.phone = record.phone;
      formState.email = record.email;
      formState.role = record.role;
      formState.status = record.status;
      formState.bio = record.bio;
      imageUrl.value = record.avatar;
      modalVisible.value = true;
    };

    // 处理弹窗确认
    const handleModalOk = () => {
      formRef.value
        .validate()
        .then(async () => {
          modalLoading.value = true;
          try {
            let response;
            if (isEdit.value) {
              response = await axios.put(`/api/user/manage/${formState.id}`, formState);
            } else {
              const submitData = { ...formState, password: encryptPassword(formState.password) };
              response = await axios.post('/api/user/manage', submitData);
            }
            if (response.data.code === 200) {
              message.success(isEdit.value ? '编辑成功' : '添加成功');
              modalVisible.value = false;
              fetchUserList();
            } else {
              message.error(response.data.message || (isEdit.value ? '编辑失败' : '添加失败'));
            }
          } catch (error) {
            console.error(isEdit.value ? '编辑用户失败:' : '添加用户失败:', error);
            message.error(isEdit.value ? '编辑失败' : '添加失败');
          } finally {
            modalLoading.value = false;
          }
        })
        .catch((error) => {
          console.log('验证失败:', error);
        });
    };

    // 处理弹窗取消
    const handleModalCancel = () => {
      modalVisible.value = false;
    };

    // 处理删除
    const handleDelete = async (id) => {
      try {
        const response = await axios.delete(`/api/user/manage/${id}`);
        if (response.data.code === 200) {
          message.success('删除成功');
          if (userList.value.length === 1 && pagination.current > 1) {
            pagination.current--;
          }
          fetchUserList();
        } else {
          message.error(response.data.message || '删除失败');
        }
      } catch (error) {
        console.error('删除用户失败:', error);
        message.error('删除失败');
      }
    };

    // 初始化获取列表
    fetchUserList();

    return {
      columns,
      userList,
      tableLoading,
      modalVisible,
      modalLoading,
      modalTitle,
      isEdit,
      formRef,
      formState,
      rules,
      pagination,
      searchForm,
      showAddModal,
      showEditModal,
      handleModalOk,
      handleModalCancel,
      handleDelete,
      handleTableChange,
      fetchUserList,
      imageUrl,
      fileList,
      beforeUpload,
      handleChange,
    };
  },
});
</script>

<style scoped>
.user-list {
  background-color: transparent;
}

.table-operations {
  margin-bottom: 16px;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.search-card {
  margin-bottom: 24px;
  border-radius: 8px;
}
</style>